package com.lc.pianostudent.activity;

import android.Manifest;
import android.app.Service;
import android.content.ComponentName;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.ServiceConnection;
import android.content.pm.PackageManager;
import android.content.res.Configuration;
import android.graphics.BitmapRegionDecoder;
import android.graphics.Typeface;
import android.hardware.Camera;
import android.media.CamcorderProfile;
import android.media.MediaMetadataRetriever;
import android.media.MediaPlayer;
import android.media.MediaRecorder;
import android.os.Bundle;
import android.os.Environment;
import android.os.Handler;
import android.os.IBinder;
import android.os.Message;
import android.os.Parcel;
import android.os.RemoteException;
import android.os.SystemClock;
import android.support.annotation.NonNull;
import android.support.v4.app.ActivityCompat;
import android.support.v4.content.ContextCompat;
import android.text.TextUtils;
import android.util.Log;
import android.view.KeyEvent;
import android.view.SurfaceHolder;
import android.view.SurfaceView;
import android.view.View;
import android.view.WindowManager;
import android.widget.ImageView;
import android.widget.TextView;
import android.widget.Toast;

import com.iceteck.silicompressorr.SiliCompressor;
import com.lc.pianostudent.BaseApplication;
import com.lc.pianostudent.R;
import com.lc.pianostudent.conn.PostHomeTypechange;
import com.lc.pianostudent.conn.PostLearnIndex;
import com.lc.pianostudent.dialog.AskDialog;
import com.lc.pianostudent.dialog.StudyDialog;
import com.lc.pianostudent.dialog.ToastDialog;
import com.lc.pianostudent.model.MyService;
import com.lc.pianostudent.util.CameraHelper;
import com.lc.pianostudent.util.Config;
import com.lc.pianostudent.util.PictureUpload;
import com.lc.pianostudent.util.RecordSettings;
import com.lc.pianostudent.util.UploadListener;
import com.lc.pianostudent.util.Util;
import com.lc.pianostudent.view.CustomProgressDialog;
import com.lc.pianostudent.view.TickProgress;
import com.qiniu.pili.droid.shortvideo.PLMediaFile;
import com.qiniu.pili.droid.shortvideo.PLShortVideoTranscoder;
import com.qiniu.pili.droid.shortvideo.PLVideoSaveListener;
import com.wonderkiln.camerakit.CameraKitError;
import com.wonderkiln.camerakit.CameraKitEvent;
import com.wonderkiln.camerakit.CameraKitEventCallback;
import com.wonderkiln.camerakit.CameraKitEventListener;
import com.wonderkiln.camerakit.CameraKitImage;
import com.wonderkiln.camerakit.CameraKitTextDetect;
import com.wonderkiln.camerakit.CameraKitVideo;
import com.wonderkiln.camerakit.CameraView;
import com.zcx.helper.bound.BoundView;
import com.zcx.helper.http.AsyCallBack;
import com.zcx.helper.util.UtilToast;

import java.io.File;
import java.io.IOException;
import java.net.URISyntaxException;
import java.text.DecimalFormat;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.Timer;
import java.util.TimerTask;

/**
 * Created by Administrator on 2018/7/6.
 */

public class StudyActivity extends BaseActivity {
    @BoundView(R.id.camera) private CameraView cameraView;
    @BoundView(R.id.count_down) private TextView mCountDown;
    @BoundView(value = R.id.begin_button,isClick = true) private ImageView begin_button;
    @BoundView(R.id.switch_button) private ImageView switch_button;
    @BoundView(R.id.time) private TextView jishi_time;
    @BoundView(value = R.id.back,isClick = true) private ImageView back_img;
    private int begin_int = 0;
    private String path;
    private CustomProgressDialog mProcessingDialog;

    private static final int MY_PERMISSIONS_REQUEST_CAMERA = 1000;
    private static final int MY_PERMISSIONS_REQUEST_RECORD = 1001;

    private SurfaceView mSurfaceView;
    private SurfaceHolder mSurfaceHolder;
    private Camera mCamera;
    private int cameraDirection = 0; // 摄像头方向
    private CamcorderProfile mProfile;
    private int preViewWidth, preViewHeight;
    private MediaRecorder mMediaRecorder;
    private int isRecord = 0;
    private String saveVideoPath;
    private boolean mIsTimerRunning = false;
    private Handler mHandler = new Handler();
    private int mCurrentTimer = 3;

    private int back = 0;  //1 后向  0 前向
    private long baseTimer;
    private Timer mTimer = null;
    private TimerTask mTimerTask = null;
    private String video_time = "";
    private List<String> pathList = new ArrayList<>();
    private PLShortVideoTranscoder mShortVideoTranscoder;
    private PLMediaFile mMediaFile;
    private int time;
    private boolean isFlase = true;
    private int last = 0; //是否是最后一次上传
    private int loading = 0; //是否正在上传
    public String currentPath = "";
    private Timer timer;
    private int last_video_time = 0;
    //我的家分类
    public PostLearnIndex postLearnIndex = new PostLearnIndex(new AsyCallBack<PostLearnIndex.PostLearnIndexInfo>(){

        @Override
        public void onSuccess(String toast, int type, Object o, PostLearnIndex.PostLearnIndexInfo postLearnIndexInfo) throws Exception {
            mProcessingDialog.dismiss();
            boolean is = Util.fileIsExists(saveVideoPath);
            if(is){
                Util.deletefile(saveVideoPath);
                Util.deletefile(currentPath);
            }

            Util.deleteLocal(new File(currentPath));
            Util.deleteLocal(new File(saveVideoPath));

            pathList.clear();
            if(last == 1){   //如果是最后一次上传 弹窗显示
                new StudyDialog(StudyActivity.this, R.layout.dialog_send_teacher,video_time){


                    @Override
                    public void cancel() {

                    }

                    @Override
                    public void confirm() {
                        finish();
//                        dismiss();
                    }
                }.show();
            }

            loading = 0;

        }

        @Override
        public void onFail(String toast, int type) throws Exception {
            UtilToast.show(toast);
            loading = 0;
        }

        @Override
        public void onStart(int type) throws Exception {

            loading = 1;
        }

        @Override
        public void onEnd(String toast, int type) throws Exception {

            loading = 0;
        }
    });
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        getWindow().setFlags(WindowManager.LayoutParams.FLAG_KEEP_SCREEN_ON, WindowManager.LayoutParams.FLAG_KEEP_SCREEN_ON);
        setContentView(R.layout.activity_study);

//        setBackTrue();

        _initView();
    }
    //计时
    final Handler startTimehandler = new Handler(){
        public void handleMessage(Message msg) {
            if (null != jishi_time) {
                jishi_time.setText((String) msg.obj);
//                video_time = (String) msg.obj;

                for(int i= 0;i<10000;i++){

                    if(i == 0){
                        if(time  == 11+(170*i)){


                            _stopRecord();

                            String hh = new DecimalFormat("00").format((time-last_video_time) / 3600);
                            String mm = new DecimalFormat("00").format((time-last_video_time)% 3600 / 60);
                            String ss = new DecimalFormat("00").format((time-last_video_time) % 60);
                            video_time = new String(hh + ":" + mm + ":" + ss);
                            last_video_time = time;
                            File file = new File(saveVideoPath);
//                            Log.e("---length",file.length()+"===");
//                            if (!TextUtils.isEmpty(saveVideoPath)) {
//                                onVideoFileSelected(saveVideoPath);
//
//                                return;
//                            }

                            pathList.add(saveVideoPath);

                            PictureUpload.getInstance(StudyActivity.this).setDatas(1,pathList,listener);
                        }
                    }else {
                        if(time  == 11+(170*i)){
                            _startRecord();
                        }
                        if(time  == 11+(170*i+11)){

                            _stopRecord();
                            String hh = new DecimalFormat("00").format((time-last_video_time) / 3600);
                            String mm = new DecimalFormat("00").format((time-last_video_time) % 3600 / 60);
                            String ss = new DecimalFormat("00").format((time-last_video_time) % 60);
                            video_time = new String(hh + ":" + mm + ":" + ss);
                            last_video_time = time;
                            File file = new File(saveVideoPath);
//                            Log.e("---length",file.length()+"===");
//                            if (!TextUtils.isEmpty(saveVideoPath)) {
//                                onVideoFileSelected(saveVideoPath);
//
//                                return;
//                            }

                            pathList.add(saveVideoPath);

                            PictureUpload.getInstance(StudyActivity.this).setDatas(1,pathList,listener);
                        }
                    }


                }

            }


        }
    };

//    //压缩视频
//    final Handler mHandlevideo = new Handler(){
//        public void handleMessage(Message msg) {
//            if(pathList.size() != 0){
//                pathList.clear();
//            }
//            pathList.add((String) msg.obj);
//
//            PictureUpload.getInstance(StudyActivity.this).setDatas(1,pathList,listener);
//        }
//    };

    //跳出弹窗
    final Handler dialogHandler = new Handler(){
        public void handleMessage(Message msg) {
            new StudyDialog(StudyActivity.this, R.layout.dialog_send_teacher,video_time){


                @Override
                public void cancel() {

                }

                @Override
                public void confirm() {
                    finish();
//                        dismiss();
                }
            }.show();
        }
    };
    private void _initView() {
        cameraDirection = Camera.CameraInfo.CAMERA_FACING_FRONT;
        mProcessingDialog = new CustomProgressDialog(this);
        mProcessingDialog.setOnCancelListener(new DialogInterface.OnCancelListener() {
            @Override
            public void onCancel(DialogInterface dialog) {
                mShortVideoTranscoder.cancelTranscode();
            }
        });
        mSurfaceView = (SurfaceView) findViewById(R.id.surface_view);
        mSurfaceHolder = mSurfaceView.getHolder();
        mSurfaceHolder.setType(SurfaceHolder.SURFACE_TYPE_PUSH_BUFFERS);
        mSurfaceHolder.setKeepScreenOn(true);
        mSurfaceHolder.addCallback(mCallback);
    }

    private SurfaceHolder.Callback mCallback = new SurfaceHolder.Callback() {

        @Override
        public void surfaceCreated(SurfaceHolder holder) {
            if (ContextCompat.checkSelfPermission(StudyActivity.this, Manifest.permission.CAMERA) != PackageManager.PERMISSION_GRANTED) {
                ActivityCompat.requestPermissions(StudyActivity.this, new String[]{Manifest.permission.CAMERA}, MY_PERMISSIONS_REQUEST_CAMERA);
                Log.e("======you","没有权限");
            } else {
                _initCamera();
                Log.e("======you","有权限");
            }
        }

        @Override
        public void surfaceChanged(SurfaceHolder holder, int format, int width, int height) {
            if (mSurfaceHolder.getSurface() == null) {
                return;
            }
        }

        @Override
        public void surfaceDestroyed(SurfaceHolder holder) {
            _stopCamera();
        }
    };

    private void _stopCamera() {
        if (mCamera != null) {
            mCamera.setPreviewCallback(null);
            mCamera.stopPreview();
            mCamera.release();
            mCamera = null;
        }
    }

    private void _initCamera() {
        if (mCamera != null) {
            _stopCamera();
        }
        try {
            mCamera = Camera.open(cameraDirection);
            mCamera.setPreviewDisplay(mSurfaceHolder);
            _setCameraParams();
            mCamera.startPreview();
        } catch (Exception e) {
            e.printStackTrace();
            _stopCamera();
            UtilToast.show("用户拒绝相机权限");
            finish();
        }

    }


    private void _setCameraParams() {
        if (mCamera != null) {
            Camera.Parameters parameters = mCamera.getParameters();
//            if (cameraDirection == Camera.CameraInfo.CAMERA_FACING_FRONT) {
//                mCamera.setDisplayOrientation(270);
//            } else {
//                mCamera.setDisplayOrientation(90);
//            }
            if (this.getResources().getConfiguration().orientation != Configuration.ORIENTATION_LANDSCAPE) {
                parameters.set("orientation", "portrait");
                mCamera.setDisplayOrientation(90);
            } else {
                parameters.set("orientation", "landscape");
                mCamera.setDisplayOrientation(0);
            }
            List<Camera.Size> mSupportedPreviewSizes = parameters.getSupportedPreviewSizes();
            List<Camera.Size> mSupportedVideoSizes = parameters.getSupportedVideoSizes();
            int width = mSurfaceView.getWidth();
            int height = mSurfaceView.getHeight();
            Camera.Size optimalSize = CameraHelper.getOptimalVideoSize(mSupportedVideoSizes, mSupportedPreviewSizes, Math.max(width, height), Math.min(width, height));
            preViewWidth = optimalSize.width;
            preViewHeight = optimalSize.height;
            Log.e("Bill", preViewWidth + "|" + preViewHeight);
            mProfile = CamcorderProfile.get(CamcorderProfile.QUALITY_HIGH);
            mProfile.videoFrameWidth = optimalSize.width;
            mProfile.videoFrameHeight = optimalSize.height;
            mProfile.videoBitRate = 2 * optimalSize.width * optimalSize.height;
            mProfile.quality = 5;

            Camera.Size optimalSize1 = getOptimalPreviewSize(mSupportedPreviewSizes, mSurfaceView.getHeight(), mSurfaceView.getWidth());
            parameters.setPreviewSize(optimalSize1.width, optimalSize1.height);

            if (parameters.getSupportedFocusModes().contains(Camera.Parameters.FOCUS_MODE_CONTINUOUS_VIDEO)) {
                parameters.setFocusMode(Camera.Parameters.FOCUS_MODE_CONTINUOUS_VIDEO);
            }
            if (parameters.isVideoStabilizationSupported()) {
                parameters.setVideoStabilization(true);
            }

//            parameters.setFocusMode(Camera.Parameters.FOCUS_MODE_CONTINUOUS_VIDEO);
//            //缩短Recording启动时间
//            parameters.setRecordingHint(true);
//            parameters.setFocusMode(Camera.Parameters.FOCUS_MODE_AUTO);
            mCamera.setParameters(parameters);
        }
    }

    private void _startRecord() {
        try {

            mCamera.unlock();
            _setConfigRecord();
            mMediaRecorder.prepare();
            mMediaRecorder.start();
        } catch (Exception e) {
            e.printStackTrace();
            finish();
            _stopRecord();
        }
    }

    private void _setConfigRecord() {
        mMediaRecorder = new MediaRecorder();
        mMediaRecorder.reset();
        mMediaRecorder.setCamera(mCamera);
        mMediaRecorder.setOnErrorListener(onErrorListener);
        mMediaRecorder.setPreviewDisplay(mSurfaceHolder.getSurface());

        Log.e("Bill", "setOutputFormat:" + mProfile.fileFormat);
        Log.e("Bill", "setVideoFrameRate:" + mProfile.videoFrameRate);
        Log.e("Bill", "setVideoSize:" + mProfile.videoFrameWidth + "|" + mProfile.videoFrameHeight);
        Log.e("Bill", "setVideoEncodingBitRate:" + mProfile.videoBitRate);
        Log.e("Bill", "setVideoEncoder:" + mProfile.videoCodec);
        Log.e("Bill", "profile.quality:" + mProfile.quality);
        Log.e("Bill", "setAudioEncodingBitRate:" + mProfile.audioBitRate);
        Log.e("Bill", "setAudioChannels:" + mProfile.audioChannels);
        Log.e("Bill", "setAudioSamplingRate:" + mProfile.audioSampleRate);
        Log.e("Bill", "setAudioEncoder:" + mProfile.audioCodec);

        mMediaRecorder.setVideoSource(MediaRecorder.VideoSource.CAMERA);
        mMediaRecorder.setAudioSource(MediaRecorder.AudioSource.MIC);
        mMediaRecorder.setProfile(mProfile);
        if(back == 1){
            mMediaRecorder.setOrientationHint(90); //后置
        }else {
            mMediaRecorder.setOrientationHint(270);  //前置
        }

        saveVideoPath = getPath() +getVideoName();
        mMediaRecorder.setOutputFile(saveVideoPath);
    }

    private String getPath() {
        String filePath = "/sdcard/Video";
        File file = new File(filePath);
        if (!file.exists()) {
            file.mkdir();
        }
        file = null;
        return filePath;
    }

    private void _stopRecord() {
        if (mMediaRecorder != null) {
            mMediaRecorder.setOnErrorListener(null);
            mMediaRecorder.setPreviewDisplay(null);
            mMediaRecorder.stop();
            mMediaRecorder.reset();
            mMediaRecorder.release();
            mMediaRecorder = null;
            if (mCamera != null)
                mCamera.lock();
        }

//        Log.e("====path",getPath()+"===jy");
//        Log.e("====",video_time+"===");
    }

    private MediaRecorder.OnErrorListener onErrorListener = new MediaRecorder.OnErrorListener() {
        @Override
        public void onError(MediaRecorder mr, int what, int extra) {

        }
    };

    @Override
    public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults) {
        super.onRequestPermissionsResult(requestCode, permissions, grantResults);
        if (requestCode == MY_PERMISSIONS_REQUEST_CAMERA) {
            if (grantResults[0] == PackageManager.PERMISSION_GRANTED) {
                _initCamera();
                Log.e("=====per","allow");
            } else {
//                Toast.makeText(this, "Permission Denied", Toast.LENGTH_SHORT).show();\
                Log.e("=====per","deny");
//                finish();
            }
        } else if (requestCode == MY_PERMISSIONS_REQUEST_RECORD) {
            if (grantResults[0] == PackageManager.PERMISSION_GRANTED) {
                _startRecord();
            } else {
                Toast.makeText(this, "Permission Denied", Toast.LENGTH_SHORT).show();
//                finish();
            }
        }
    }
    //切换摄像头
    public void handleSwitch(View view) {
        if (cameraDirection == Camera.CameraInfo.CAMERA_FACING_FRONT) {
            cameraDirection = Camera.CameraInfo.CAMERA_FACING_BACK;
            back = 1;
        } else {
            cameraDirection = Camera.CameraInfo.CAMERA_FACING_FRONT;
            back = 0;
        }
        _initCamera();
    }

//    点击开始
    public void handleRecord(View view) {
        if (ContextCompat.checkSelfPermission(StudyActivity.this, Manifest.permission.RECORD_AUDIO) != PackageManager.PERMISSION_GRANTED) {
            ActivityCompat.requestPermissions(StudyActivity.this, new String[]{Manifest.permission.RECORD_AUDIO}, MY_PERMISSIONS_REQUEST_RECORD);
        } else {
            //点击开始
            if(isRecord == 0){
                switch_button.setVisibility(View.INVISIBLE);
                //倒计时
                if (!mIsTimerRunning) {
                    mIsTimerRunning = true;
                    mHandler.post(timerRunnable);
                }

            }else {
                //点击结束
                _stopRecord();
                begin_button.setImageResource(R.mipmap.study_default);
                isRecord = 0;
                switch_button.setVisibility(View.VISIBLE);
                last =1;
                stopTimer();
//                Log.e("====",saveVideoPath+"===");


                if (!TextUtils.isEmpty(saveVideoPath)) {
                    File file = new File(saveVideoPath);
//                    Log.e("====",file.length()+"===");
                    if(file.length() == 0){  //没有流，处于间隔时间，模拟上传视频的状态，假上传
                        mProcessingDialog.show();
                        new Thread(new Runnable() {
                            @Override
                            public void run() {
                                int i = 0;
                                while (i < 100) {
                                    try {
                                        Thread.sleep(100);
                                        // 更新进度条的进度,可以在子线程中更新进度条进度
                                        mProcessingDialog.incrementProgressBy(1);
                                        // dialog.incrementSecondaryProgressBy(10)//二级进度条更新方式
                                        i++;
                                    } catch (Exception e) {
                                    }
                                }
                                // 在进度条走完时删除Dialog
                                mProcessingDialog.dismiss();
                                Message msg = new Message();
                                dialogHandler.sendMessage(msg);
                            }
                        }).start();

                    }else {
                        if(loading == 0){  //证明还没有上传
                            String hh = new DecimalFormat("00").format((time-last_video_time) / 3600);
                            String mm = new DecimalFormat("00").format((time-last_video_time)% 3600 / 60);
                            String ss = new DecimalFormat("00").format((time-last_video_time) % 60);
                            video_time = new String(hh + ":" + mm + ":" + ss);
                            onVideoFileSelected(saveVideoPath);  //真正上传
                        }else {
                            mProcessingDialog.show();
                            new Thread(new Runnable() {
                                @Override
                                public void run() {
                                    int i = 0;
                                    while (i < 100) {
                                        try {
                                            Thread.sleep(200);
                                            // 更新进度条的进度,可以在子线程中更新进度条进度
                                            mProcessingDialog.incrementProgressBy(1);
                                            // dialog.incrementSecondaryProgressBy(10)//二级进度条更新方式
                                            i++;
                                        } catch (Exception e) {
                                        }
                                    }
                                    // 在进度条走完时删除Dialog
                                    mProcessingDialog.dismiss();
                                    Message msg = new Message();
                                    dialogHandler.sendMessage(msg);
                                }
                            }).start();
                        }

                    }


                    return;
                }



            }


        }

    }
//    上传文件到oss
    UploadListener listener =new UploadListener() {
        @Override
        public void onUploadComplete(int position, List<String> success, List<String> failure) {
           /* Log.v("sly","上传完毕");
            for (int i = 0; i < success.size(); i++) {
                Log.v("sly",success.get(i).toString());
            }*/
            if (position==1&&success.size()==pathList.size()){

//                Log.e("=====",success.get(0)+"===");
                postLearnIndex.user_id = BaseApplication.BasePreferences.readUID();
                postLearnIndex.time = video_time;
                postLearnIndex.video = success.get(0);
                postLearnIndex.execute();


            }else {

                UtilToast.show("文件上传失败");
//                if (dialog!=null){
//                    dialog.dismiss();
//                    dialog=null;
//                }
            }

        }
    };
    //倒计时
    private Runnable timerRunnable = new Runnable() {
        @Override
        public void run() {
            if (mCurrentTimer > 0) {
                mCountDown.setText(mCurrentTimer + "");

                mCurrentTimer--;
                mHandler.postDelayed(timerRunnable, 1000);
            } else {

                mCountDown.setText("");

                mIsTimerRunning = false;
                mCurrentTimer = 3;  //从3s开始倒计时

//                Toast.makeText(StudyActivity.this,"开始了",Toast.LENGTH_SHORT).show();

                _startRecord();
                begin_button.setImageResource(R.mipmap.study_video);
                isRecord = 1;
                //开始计时
                startTimer();
            }
        }
    };


    @Override
    protected void onDestroy() {
        super.onDestroy();
        _stopRecord();
        _stopCamera();

        if (mMediaFile != null) {
            mMediaFile.release();
        }
    }

    private String getVideoName() {
        return "VID_" + new SimpleDateFormat("yyyyMMdd_HHmmss").format(new Date()) + ".mp4";
    }

    //录像开始计时
    public void startTimer(){
        if (mTimer == null) {
            mTimer = new Timer();
        }
        StudyActivity.this.baseTimer = SystemClock.elapsedRealtime();
        if (mTimerTask == null) {
            mTimerTask = new TimerTask() {
                @Override
                public void run() {

                    time = (int)((SystemClock.elapsedRealtime() - StudyActivity.this.baseTimer) / 1000);
                    String hh = new DecimalFormat("00").format(time / 3600);
                    String mm = new DecimalFormat("00").format(time % 3600 / 60);
                    String ss = new DecimalFormat("00").format(time % 60);
                    String timeFormat = new String(hh + ":" + mm + ":" + ss);
                    Message msg = new Message();
                    msg.obj = timeFormat;
                    startTimehandler.sendMessage(msg);
                }
            };
        }

        if(mTimer != null){
            mTimer.schedule(mTimerTask, 0, 1000L);//1000ms执行一次
        }
    }

    //停止录像后计时取消
    public void stopTimer(){

        if (mTimer != null) {
            mTimer.cancel();
            mTimer = null;
        }

        if (mTimerTask != null) {
            mTimerTask.cancel();
            mTimerTask = null;
        }

    }
    //预览不变形
    private Camera.Size getOptimalPreviewSize(List<Camera.Size> sizes, int w, int h) {
        final double ASPECT_TOLERANCE = 0.1;
        double targetRatio = (double) w / h;
        if (sizes == null) return null;

        Camera.Size optimalSize = null;
        double minDiff = Double.MAX_VALUE;

        int targetHeight = h;

        // Try to find an size match aspect ratio and size
        for (Camera.Size size : sizes) {
            double ratio = (double) size.width / size.height;
            if (Math.abs(ratio - targetRatio) > ASPECT_TOLERANCE) continue;
            if (Math.abs(size.height - targetHeight) < minDiff) {
                optimalSize = size;
                minDiff = Math.abs(size.height - targetHeight);
            }
        }

        // Cannot find the one match the aspect ratio, ignore the requirement
        if (optimalSize == null) {
            minDiff = Double.MAX_VALUE;
            for (Camera.Size size : sizes) {
                if (Math.abs(size.height - targetHeight) < minDiff) {
                    optimalSize = size;
                    minDiff = Math.abs(size.height - targetHeight);
                }
            }
        }
        return optimalSize;
    }
    //切换摄像头
    public void handleBack(View view) {
        finish();
    }

    private void onVideoFileSelected(String filepath) {
//        Log.e("====file",filepath+"++++");
        mShortVideoTranscoder = new PLShortVideoTranscoder(this, filepath, getPath() +getVideoName());
        mMediaFile = new PLMediaFile(filepath);
//        String bitrate = (mMediaFile.getVideoBitrate() / 1000) + " kbps";
        doTranscode(false);
    }

//    压缩视频
    private void doTranscode(boolean isReverse) {
        Log.i("MAIN", "save failed: ");
        if (mShortVideoTranscoder == null) {
            UtilToast.show("请先选择转码文件！");
            return;
        }
        int transcodingWidth = Integer.parseInt("720");
        int transcodingHeight = Integer.parseInt("1280");
        boolean startResult =  mShortVideoTranscoder.transcode(
                transcodingWidth, transcodingHeight, RecordSettings.ENCODING_BITRATE_LEVEL_ARRAY[0],
                RecordSettings.ROTATION_LEVEL_ARRAY[0], false,new PLVideoSaveListener() {
                    @Override
                    public void onSaveVideoSuccess(final String s) {
                        runOnUiThread(new Runnable() {
                            @Override
                            public void run() {


//                                showChooseDialog(s);
//                                Log.e("=====s",s+"====");
                                currentPath = s;
                                pathList.add(s);

//
                                PictureUpload.getInstance(StudyActivity.this).setDatas(1,pathList,listener);
                            }
                        });

                    }

                    @Override
                    public void onSaveVideoFailed(final int errorCode) {
                        runOnUiThread(new Runnable() {
                            @Override
                            public void run() {
                                mProcessingDialog.dismiss();

                            }
                        });
                    }

                    @Override
                    public void onSaveVideoCanceled() {
                        runOnUiThread(new Runnable() {
                            @Override
                            public void run() {
                                mProcessingDialog.dismiss();
                            }
                        });
                    }

                    @Override
                    public void onProgressUpdate(final float percentage) {
                        runOnUiThread(new Runnable() {
                            @Override
                            public void run() {
                                if(last == 1){
                                    mProcessingDialog.setProgress((int) (100 * percentage));
                                }

                            }
                        });
                    }
                });
        if (startResult) {
            if(last == 1){
                mProcessingDialog.show();
            }
//
        } else {

        }
    }
    //返回键
    @Override
    public boolean onKeyDown(int keyCode, KeyEvent event) {
        if ((keyCode == KeyEvent.KEYCODE_BACK)) {
            new AskDialog(this, R.layout.ask_exit_study) {
                @Override
                public void cancel() {

                }

                @Override
                public void confirm() {
                    stopTimer();
                    finish();
                }
            }.show();
            return false;
        } else {
            return super.onKeyDown(keyCode, event);
        }
    }


}
